from flask_login import current_user
from werkzeug.security import generate_password_hash
from wtforms import StringField

from app.database.models import AdminUser
from app.server.flask_app.model_views.CustomModelView import CustomModelView
from app.server.flask_app.model_views.mixins.AuthMixin import AuthMixin


class CustomPasswordField(
    StringField
):  # If you don't want hide the password you can use a StringField
    def populate_obj(self, obj, name):
        setattr(obj, name, generate_password_hash(self.data, method="sha256"))


class AdminModelView(AuthMixin, CustomModelView):

    column_editable_list = ["email", "password", "name", "is_super_admin"]
    column_searchable_list = column_editable_list
    column_filters = column_editable_list

    def __init__(self, session, **kwargs):
        super(AdminModelView, self).__init__(AdminUser, session, **kwargs)

    @property
    def can_create(self):
        return current_user.is_super_admin

    @property
    def can_edit(self):
        return current_user.is_super_admin

    @property
    def can_delete(self):
        return current_user.is_super_admin

    form_extra_fields = {"password": CustomPasswordField("Password")}
